var app = getApp(), u = app.require("utils/util.js"), a = app.require("utils/api.js"), o = app.require("utils/onfire.js"), h = app.require("utils/http.js"), n = app.require("utils/enums");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList:[],
    userInfo:null,
    source:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {   
    this.data.source = options.source;    
  },
  onShow:function(){
    var t = this;
    if (wx.getStorageSync('userInfo')) {
      t.data.userInfo = wx.getStorageSync('userInfo'),
      t.getAddressList();
    } else {
      app.callAuthorize(function (userinfo) {
        t.data.userInfo = userinfo,
        t.getAddressList();
      });
    } 
  },
  // 获取用户所有收货地址列表
  getAddressList:function(){
    var t = this;
    var data = { uid: t.data.userInfo.uid};
    console.log(a);
    h.postReq(a.addressListUrl, data, function (res) {
      if (res.code == 0) {
        t.setData({
          addressList: res.data.info
        })
      }else {
        u.toast(res.message);
      }
    });
  },
  // 切换默认地址
  checkAddress:function(e){
    var t = this;
    var id = e.currentTarget.dataset.id;
    var data = { 
      uid: t.data.userInfo.uid,
      address_id: id
    };
    h.postReq(a.checkAddressUrl, data, function (res) {
      if (res.code == 0) {
        t.getAddressList();
      }else {
        u.toast(res.message);
      }
    });
  },
  // 删除收货地址
  delAddress:function(e){
    var t = this;
    var id = e.currentTarget.dataset.id;
    var data = {
      uid: t.data.userInfo.uid,
      address_id: id
    };
    u.confirm('是否删除？',function(){
      h.postReq(a.deleteAddressUrl, data, function (res) {
        if (res.code == 0) {
          t.getAddressList();
        }else {
          u.toast(res.message);
        }
      });
    });
   
  },
  // 跳转新增收货地址页面
  toAdd:function(){
    wx.navigateTo({
      url: 'add',
    })
  },
  toEdit(e){
    var t = this;
    var address_id = e.currentTarget.dataset.id;
    var data = [];
    for (var i = 0; i < t.data.addressList.length; i++){
      if (t.data.addressList[i].address_id == address_id){
        data = t.data.addressList[i];
        o.fire("editAddress",data);
      }
    }
    // console.log(data);return;
    wx.navigateTo({
      url: 'add?address_id=' + address_id,
    })
  },
  checkAddressByPay:function(e){
    if (this.data.source == 'pay'){
      this.checkAddress(e),
      wx.navigateBack({ changed: true });//返回上一页
    }    
  },
})